<template>
	<div class="content" id="scrollDiv">
		<scroll-view
			id="scroll-view"
			class="list_box"
			:scroll-into-view="intoView"
			@scroll="onScroll"
			@scrolltoupper="handleScrollToUpper"
			scroll-y
			:style="{ height: `calc(100vh - ${105}px)` }"
		>
			<p class="head_tips">在这可以直接私信互动了～</p>
			<div 
				:id="`item${index}`"
				class="list" 
				v-for="(item, index) in dataList" 
				:key="index"
			>
				<div class="time">{{ item.createDate }}</div>

				<div class="left" v-if="userId != item.sendUserId">
					<img :src="item.avatar ? item.avatar : '/static/mr_tx.png'" alt="" />
					<p v-if="!item.pictureList" class="text" selectable>{{ item.message }}</p>
					<p v-else class="text" selectable>
						<img @click="previewImg(item.pictureList[0])" :src="item.pictureList[0]" alt="" />
					</p>
				</div>
				<div class="right" v-else>
					<p v-if="!item.pictureList" class="text" selectable>{{ item.message }}</p>
					<p v-else class="text" selectable>
						<img @click="previewImg(item.pictureList[0])" :src="item.pictureList[0]" alt="" />
					</p>
					<img :src="item.avatar ? item.avatar : '/static/mr_tx.png'" alt="" />
					<div class="shenhe" v-if="item.status === 1">
						<u-icon name="info-circle" color="#23AC39" size="12"></u-icon>
						<span>审核中</span>
					</div>
					<div class="shenhe on" v-if="item.status === 3">
						<u-icon name="info-circle" color="#ff4441" size="12"></u-icon>
						<span>审核失败</span>
					</div>
				</div>
			</div>
		</scroll-view>

		<div class="input_box">
			<div class="box">
				<div class="label">
					<p @click="toLocal">
						<img src="/static/s_icon1.png" alt="" />本地一手
					</p>
					<p @click="show = true">
						<img src="/static/s_icon2.png" alt="" />联系方式
					</p>
					<p v-if="!userMsg.state" @click="clickPb">
						<img src="/static/s_icon3.png" alt="" />屏蔽私信
					</p>
					<p class="on" v-else @click="clickPb">
						<img src="/static/s_icon3_on.png" alt="" />已屏蔽
					</p>
					<p @click="toExposure">
						<img src="/static/bg_user.png" alt="" />曝光他
					</p>
				</div>
				<div class="sr_input" ref="container">
					<u--textarea :adjustPosition="false" v-model="input_value" cursorSpacing="300"
						:showConfirmBar="false" height="19px" @focus="changeFocus" @blur="changeBlur"
						placeholder="请输入内容" autoHeight></u--textarea>
					<p @click="sendOut">发送</p>
					<img v-if="!upHeight" @click="addUpImg" src="/static/plus-add.png" alt="" />
					<img v-else @click="hideUpImg" src="/static/plus-add.png" alt="" />
				</div>
				<div @click="changeImg" class="up_img" :style="{ height: upHeight + 'rpx' }">
					<p class="img">
						<img src="/static/up_img.png" alt="" />
					</p>
					<p class="text">图片</p>
				</div>
				<div :style="{ height: keyboardHeight + 'px' }"></div>
			</div>
		</div>

		<u-action-sheet 
			@select="selectTab"
			@close="show = false"
			cancelText="取消"
			:actions="list" 
			:closeOnClickOverlay="true" 
			:closeOnClickAction="true"  
			:title="title" 
			:show="show"
		></u-action-sheet>
	</div>
</template>

<script>
	import {
		mapState,
		mapActions
	} from "vuex";
	import api from "@/api";
	import WebsocketTask from "./websocket.js";
	import Config from "@/config/index.js";
	import {
		formatTimestamp
	} from "@/utils/utils.js";
	import { getUserToken } from '@/utils/auth';
	export default {
		data() {
			return {
				show: false,
				list: [
					{
						name: "微信号",
					},
					{
						name: "手机号",
					},
				],
				input_value: "",
				dataList: [],
				websocket: null,
				newId: "",
				bAvatar: "",
				param: {
					memberUserId: "",
					sendUserId: "",
					pageNo: 0,
					pageSize: 10,
				},
				setData: {},
				upHeight: 0,
				keyboardHeight: 0,
				userMsg: {},
				intoView: "",
				scrollTop: 0, // 滚动条位置
				reply: false
			};
		},
		computed: {
			...mapState({
				userTx: (state) => state.user.userTx,
				baseurl: (state) => state.user.baseurl,
				token: (state) => state.user.token,
				userId: (state) => state.user.userId,
				userName: (state) => state.user.userName,
			}),
			//仅展示审批通过的消息
			// approvedList() {
			// 	return this.dataList.filter((v) => v.status === 2);
			// },
		},
		onLoad(options) {
			if (options.reply) {
				this.reply = options.reply === 'true';
			}
            console.log(this.reply);
			this.setData = JSON.parse(options.setData);
			console.log(this.setData);
			this.param.memberUserId = this.userId;
			this.param.sendUserId = this.setData.chatUserId;
			uni.setNavigationBarTitle({
				title: this.reply?this.setData.memberUserName:this.setData.chatUserName,
			});
			this.getList(true);

			this.getUserState();
		},
		onUnload() {
			uni.closeSocket({
				success: () => {
					console.log("WebSocket连接已关闭");
				},
			});
		},
		onShow() {
			console.log('aaaa111')
			// let websocket = new WebsocketTask(`ws://192.168.0.104:48080/infra/ws?token=${this.token}`);
			// 发送消息
			uni.connectSocket({
				url: `${Config.apiSocket}${getUserToken()}`, // WebSocket服务器地址
				header: {
					"content-type": "application/json",
				},
			});

			// 连接打开
			uni.onSocketOpen(function(res) {
				console.log("WebSocket连接已打开");
			});

			// 接收消息
			uni.onSocketMessage((res) => {
				console.log("收到WebSocket服务器消息：", res.data);

				const jsonMessage = JSON.parse(res.data);
				const type = jsonMessage.type;
				const content = JSON.parse(jsonMessage.content);
				const {
					avatar,
					message,
					nickName,
					pictureList,
					status,
					createDate
				} = JSON.parse(
					content.text
				);
				console.log(type);
				console.log(content);
				if (pictureList && pictureList.length) {
					this.dataList.push({
						avatar,
						status,
						img: pictureList[0],
						sendUserId: content.fromUserId,
						createDate: formatTimestamp(createDate),
					});
				} else {
					this.dataList.push({
						avatar,
						message,
						status,
						sendUserId: content.fromUserId,
						createDate: formatTimestamp(createDate),
					});
				}

				this.intoView = `item${this.dataList.length - 1}`
				if (!type) {
					return;
				}
			});
		},
		mounted() {
			// #ifdef APP-PLUS || H5 || MP-WEIXIN
			uni.onKeyboardHeightChange(res => {
				this.keyboardHeight = res.height; // 单位是 px，直接可用
			});
			// #endif
		},
		beforeDestroy() {
			// #ifdef APP-PLUS || H5 || MP-WEIXIN
			uni.offKeyboardHeightChange();
			// #endif
		},
		methods: {
			handleScrollToUpper() {
				if (this.scrollTop < 1000) {
					console.log("滚动到顶部了")
					// this.loadingShow = true
					// this.isFx = false
					this.param.pageSize = 10
					this.param.pageNo++
					this.getList(false)
				}
			},
			onScroll(event) {
				const deltaY = event.detail.deltaY
				this.scrollTop = event.detail.scrollTop
				// if (deltaY > 0) {
				//   this.isFx = true
				// } else {
				//   this.isFx = false
				// }
			},

			selectTab(e){
				console.log(e);
				if (!e.index) {
					uni.setClipboardData({
						data: e.name,
						success: () => {
							uni.showToast({
								title: '复制成功',
								icon: 'none'
							});
						},
						fail: (err) => {
							console.error('复制失败', err);
						}
					});
				} else {
					this.makePhoneCall()
				}
			},
			onBackPress(options) {
				console.log('onBackPress options:', options);
				// options.from can be 'navigateBack', 'backbutton' (physical back button on Android), or 'navigateBackMiniProgram' (for mini-programs)
				if (options.from === 'backbutton') {
					// Perform your custom logic here, e.g., show a confirmation dialog
					uni.showModal({
						title: '提示',
						content: '确定要退出聊天吗？',
						success: function (res) {
							if (res.confirm) {
								// If the user confirms, then proceed with the default back navigation
								uni.navigateBack({ delta: 1 });
							} else if (res.cancel) {
								// User cancelled, do nothing or handle as needed
								console.log('用户点击取消');
							}
						}
					});
					// Return true to prevent the default back button action
					return true; 
				}
				// Return false to allow the default back button action for other cases (like uni.navigateBack)
				return false; 
			},

			getUserState() {
				let data = {
					userId: this.userId,
					screenUserId: this.param.sendUserId,
				};
				api.user.user_chat(data).then((res) => {
					if (res.code == 200) {
						this.list[0].name = res.data.wechatId && res.data.wechatId !='null' ? '微信号：'+res.data.wechatId : '暂无微信号';
						this.list[1].name = '手机号：'+res.data.mobile;
						this.userMsg = res.data;
					}
				});
			},

			clickPb() {
				let state = this.userMsg.state;
				uni.showModal({
					title: "提示",
					content: state ? "是否取消屏蔽此用户" : "是否屏蔽此用户",
					showCancel: true,
					cancelText: "取消",
					confirmText: "确定",
					success: (res) => {
						if (res.confirm) {
							let data = {
								userId: this.userId,
								screenUserId: this.param.memberUserId,
								state: state ? 0 : 1,
							};
							api.user.update_screen(data).then((res) => {
								if (res.code == 200) {
									this.getUserState();
								}
							});
						}
					},
				});
			},

			makePhoneCall() {
				uni.makePhoneCall({
					phoneNumber: this.userMsg.mobile, // 替换为实际电话号码
					success: () => {
						console.log("拨打电话成功");
					},
					fail: (err) => {
						console.error("拨打电话失败", err);
					},
				});
			},

			

			// changeFocus() {
			// 	this.keyboardHeight = 300;
			// },
			// changeBlur() {
			// 	this.keyboardHeight = 0;
			// },

			// 跳转曝光
			toExposure() {
				console.log(this.param.memberUserId);
				uni.navigateTo({
					url: `/pages/exposure/index?bgName=${this.setData.memberUserName}&memberId=${this.param.memberUserId}`,
				});
			},

			previewImg(imgurl) {
				uni.previewImage({
					current: imgurl, // 当前显示图片的http链接
					urls: [imgurl], // 需要预览的图片http链接列表
				});
			},

			changeImg() {
				uni.chooseImage({
					count: 1, // 默认最多可以选择的图片张数
					sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
					success: (item) => {
						console.log("aaaa");
						console.log(item);
						uni.showModal({
							title: "提示",
							content: "确定发送该图片",
							showCancel: true,
							cancelText: "取消",
							confirmText: "确定",
							success: (res) => {
								if (res.confirm) {
									uni.showLoading({
										title: "发送中..."
									});
									uni.uploadFile({
										url: `${Config.apiUpload}`,
										name: "file",
										method: "POST",
										filePath: item.tempFilePaths[0],
										header: {
											Authorization: `Bearer ${this.token}`,
										},
										formData: {
											file: item.tempFilePaths[0],
										},
										success: (res) => {
											let returnData = JSON.parse(res.data);
											this.input_value = "";
											this.setMsgSubmit(false, returnData.data);
										},
										fail: (err) => {
											uni.hideLoading();
											this.$toast("发送失败，请重新上传！");
										},
									});
								}
							},
						});
					},
				});
			},

			addUpImg() {
				this.upHeight = 150;
			},

			hideUpImg() {
				this.upHeight = 0;
			},

			toLocal() {
				uni.navigateTo({
					url: "/pages/local/index",
				});
			},

			// 获取消息
			async getList(state) {
				this.intoView = ""
				await api.user.chat_list(this.param).then((res) => {
					if (res.code == 200) {
						if (state) {
							this.dataList = []
						}
						if (this.param.pageNo && !res.data.list.length) {
							return
						}
						res.data.list.map((item) => {
							item.createDate = formatTimestamp(item.createDate)
						});

						this.dataList = res.data.list.concat(this.dataList);
						console.log(this.dataList);
						this.$nextTick(() => {
							if (state) {
								this.intoView = `item${this.dataList.length - 1}`
							} else {
								this.intoView = `item11`
							}
						})
						console.log("intoView", this.intoView)
					}
				});
			},

			setMsgSubmit(state, img) {
				uni.hideLoading();
				let messageContent = {};
				let state_s = 0;
				// 都没屏蔽
				if (!this.userMsg.coverState && this.userMsg.state) {
					state_s = 0;
				}
				if (!this.userMsg.coverState && this.userMsg.state) {
					state_s = 1; // 我屏蔽
				}
				if (this.userMsg.coverState && !this.userMsg.state) {
					state_s = 2; // 对方屏蔽
				}
				if (this.userMsg.coverState && this.userMsg.state) {
					state_s = 3; // 双方屏蔽
				}
				if (state) {
					// 发送文字
					messageContent = JSON.stringify({
						toUserId: this.param.memberUserId,
						text: JSON.stringify({
							message: this.input_value,
							state: state_s,
						}),
					});
				} else {
					// 发送图片
					messageContent = JSON.stringify({
						toUserId: this.param.memberUserId,
						text: JSON.stringify({
							pictureList: [img],
							state: state_s,
						}),
					});
				}
				console.log(messageContent);

				// JSON 化整个消息
				let jsonMessage = JSON.stringify({
					type: "chat-message-send",
					content: messageContent,
				});

				uni.sendSocketMessage({
					data: jsonMessage,
				});

				// 第一次创建私聊
				// if(!this.dataList.length){
				// 	let data = {
				// 		newId:this.setData.id,
				// 		message:this.input_value,
				// 		memberUserId:this.userId,
				// 		chatUserId:this.param.memberUserId,
				// 		avatar:this.setData.bAvatar,
				// 		memberUserName:this.setData.memberUserName,
				// 		chatUserName:this.userName
				// 	}
				// 	console.log(data)
				// 	api.user.message_create(data).then(res=>{

				// 	})
				// }
				let data = {}
				if (this.reply) {
					console.log('回复私信')
					data = {
						newId: this.setData.id,
						message: this.input_value,
						memberUserId: this.userId,
						memberUserName: this.userName,
						chatUserId: this.setData.chatUserId,
						chatUserName: this.reply?this.setData.memberUserName: this.setData.chatUserName,
						avatar: this.setData.bAvatar,
						pictureList: img && [img],
						reply: this.reply
					}
				} else {
					console.log('私信别人')
					data = {
						newId: this.setData.id,
						message: this.input_value,
						memberUserId: this.userId,
						memberUserName: this.userName,
						chatUserId: this.setData.chatUserId,
						chatUserName: this.setData.chatUserName,
						avatar: this.setData.bAvatar,
						pictureList: img && [img],
						reply: this.reply
					}
				}
				console.log(data);
				api.user.message_create(data).then((res) => {
					if (res.code !== 200) {
						this.$toast(res.msg)
					}
				});

				// if (state) {
				// 	// 发送文字
				// 	this.dataList.push({
				// 		avatar: this.userTx,
				// 		message: this.input_value,
				// 		fromUserId: this.userId,
				// 		createDate: formatTimestamp(Date.now()),
				// 	});
				// } else {
				// 	this.dataList.push({
				// 		avatar: this.userTx,
				// 		img,
				// 		fromUserId: this.userId,
				// 		createDate: formatTimestamp(Date.now()),
				// 	});
				// }
				this.input_value = "";
				this.scrollToBottom();
			},

			// 发送信息
			sendOut() {
				if (!this.input_value) {
					return;
				}
				this.setMsgSubmit(true);
			},

			// 内容到底向上移动
			scrollToBottom() {
				const query = uni.createSelectorQuery();
				query.select("#scrollDiv").boundingClientRect((rect) => {
					if (rect) {
						uni.pageScrollTo({
							scrollTop: rect.height,
							duration: 200,
						});
					}
				});
				query.exec();
			},
		},
	};
</script>

<style lang="scss" scoped>
	$tx_height: 92rpx;
	$tx_margin: 18rpx;
	$input_an_height: 80rpx;
	.list_box {
		width: 100%;
		background: #fff;
		// margin-top:-46rpx;
		border-radius: 20rpx 20rpx 0px 0px;
		position: relative;
		z-index: 10;

		// height: calc(100vh - 105px - 115px);
		.loading_more {
			margin: 30rpx 0;
		}
	}
	.content {
		min-height: 100vh;
		padding: 0 26rpx;

		.head_tips {
			text-align: center;
			color: #999999;
			font-size: 26rpx;
			padding: 30rpx 0 20rpx 0;
		}

		.list {
			&:first-child {
				.time {
					padding-top: 30rpx;
				}
			}

			.time {
				text-align: center;
				padding-bottom: 30rpx;
				font-size: 24rpx;
				color: #999999;
			}

			.left {
				width: 100%;
				display: flex;
				margin-bottom: 40rpx;

				img {
					width: $tx_height;
					height: $tx_height;
					border-radius: 8rpx;
				}

				.text {
					max-width: 80%;
					background: #f5f5f5;
					margin: 0 0 0 $tx_margin;
					font-size: 30rpx;
					color: #333;
					padding: 24rpx;
					border-radius: 0 20rpx 20rpx 20rpx;
					word-wrap: break-word;
					overflow-wrap: break-word;

					img {
						width: 300rpx;
						height: 300rpx;
					}
				}
			}

			.right {
				position: relative;
				@extend .left;
				justify-content: flex-end;

				.text {
					background: #23ac39;
					color: #fff;
					margin: 0 $tx_margin 0 0;
					border-radius: 20rpx 0rpx 20rpx 20rpx;
				}
			}
		}

		.input_box {
			width: 100%;
			max-height: 220rpx;

			.box {
				width: 94%;
				position: fixed;
				bottom: 0;
				left: 0;
				padding: 24rpx;
				padding-top: 0;
				z-index: 10;
				background: #f1f1f1;
				box-shadow: 0px 8rpx 20rpx 0px rgba(0, 0, 0, 0.5);

				.label {
					margin-bottom: 20rpx;
					display: flex;
					flex-wrap: wrap;

					p {
						display: flex;
						align-items: center;
						padding: 12rpx 16rpx;
						background: #fff;
						border-radius: 10rpx;
						margin-right: 14rpx;
						color: #23ac39;
						font-size: 24rpx;
						margin-top: 24rpx;

						&:last-child {
							margin-right: 0;
						}

						img {
							width: 30rpx;
							height: 30rpx;
							margin-right: 10rpx;
						}

						&.on {
							color: #ff4441;
						}
					}
				}

				.sr_input {
					display: flex;
					align-items: center;
					justify-content: space-between;

					/deep/ .u-textarea {
						width: 66%;
						background: #fff;
						padding: 24rpx;
						border-radius: 10rpx;
						font-size: 28rpx;
						flex: inherit;
						border: none;
						-webkit-appearance: none;
						color: #000;
					}

					p {
						width: 108rpx;
						height: $input_an_height;
						line-height: $input_an_height;
						background: #23ac39;
						border-radius: 10rpx;
						font-size: 28rpx;
						color: #fff;
						text-align: center;
					}

					img {
						width: 48rpx;
						height: 48rpx;
					}
				}

				.up_img {
					height: 0;
					transition: all 0.3s;
					width: 150rpx;
					overflow: hidden;

					.img {
						width: 80rpx;
						height: 80rpx;
						background: #fff;
						border-radius: 10rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						margin: 30rpx 0 0 30rpx;

						img {
							width: 50rpx;
							height: 50rpx;
						}
					}

					.text {
						width: 80rpx;
						margin-left: 30rpx;
						text-align: center;
						font-size: 22rpx;
						margin-top: 10rpx;
						color: #999;
					}
				}
			}
		}
	}
	.shenhe {
		position: absolute;
		bottom: -40rpx;
		right: 110rpx;
		font-size:28rpx;
		color: #23ac39;
		display: flex;
		span {
			margin-left: 6rpx;
		}
		&.on {
			color: #ff4441;
		}
	}
</style>
